package com.jj.core.rpc;

import com.alibaba.fastjson.JSON;
import com.jj.aop.annotation.RPC;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.util.HashMap;
import java.util.Map;


public class RPCManagerTest {
    private static Logger logger = LoggerFactory.getLogger(RPCManagerTest.class);

    RPCManager manager = new RPCManager();

    public RPCManager getManager() {
        if(manager.getRpcUtils() == null){
            manager.setRpcUtils(new RPCUtils());
            manager.getRpcUtils().init();
        }
        return manager;
    }

    public void setManager(RPCManager manager) {
        this.manager = manager;
    }

    public void run() throws RPCManager.RPCNotFoundException, RPCManager.RPCException {
        TestHandler handler = new TestHandler();
        getManager().regRPCHandler(handler);

        Map args = new HashMap<>();
        args.put("name", "tom");
        args.put("age", 9);
        String jsonMapStr = JSON.toJSONString(args);
        logger.debug("jsonMapStr:{}", jsonMapStr);
        Object ret = getManager().call(1, jsonMapStr, null);
        logger.debug("map rpc ret:{}", ret);
        ret = getManager().callGeneric(1,  "hello_world,999".split(","), null);
        logger.debug("generic rpc ret:{}", ret);
    }

    public static void main(String[] args) throws RPCManager.RPCNotFoundException, RPCManager.RPCException {
        RPCManagerTest test = new RPCManagerTest();
        test.run();
    }

    public static class TestHandler extends RPCHandler{
        @RPC(id=1, args = {"name","age"})
        public String hello(String name, Integer age){
            return "hello " + name + ", age:" + age;
        }
    }
}
